<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <p>管理系统用户账号、权限和状态</p>
    </div>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="showAddUserDialog">
          <i class="el-icon-plus"></i>
          添加用户
        </el-button>
        <el-button type="danger" @click="batchDeleteUsers" :disabled="selectedUsers.length === 0">
          <i class="el-icon-delete"></i>
          批量删除
        </el-button>
        <el-button type="warning" @click="exportUsers">
          <i class="el-icon-download"></i>
          导出用户
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名、邮箱或角色"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
        </el-input>
        <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px; margin-left: 10px">
          <el-option label="全部" value=""></el-option>
          <el-option label="正常" value="normal"></el-option>
          <el-option label="禁用" value="disabled"></el-option>
        </el-select>
        <el-select v-model="roleFilter" placeholder="角色筛选" style="width: 120px; margin-left: 10px">
          <el-option label="全部" value=""></el-option>
          <el-option label="管理员" value="admin"></el-option>
          <el-option label="普通用户" value="user"></el-option>
        </el-select>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-table">
      <el-table
        :data="filteredUsers"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="avatar" label="头像" width="80">
          <template #default="scope">
            <el-avatar :size="40" :src="scope.row.avatar" :alt="scope.row.username">
              {{ scope.row.username.charAt(0) }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="150">
          <template #default="scope">
            <div class="user-info">
              <div class="username">{{ scope.row.username }}</div>
              <div class="user-id">ID: {{ scope.row.id }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'normal' ? 'success' : 'warning'">
              {{ scope.row.status === 'normal' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editUser(scope.row)">
              编辑
            </el-button>
            <el-button
              :type="scope.row.status === 'normal' ? 'warning' : 'success'"
              size="small"
              @click="toggleUserStatus(scope.row)"
            >
              {{ scope.row.status === 'normal' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="deleteUser(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalUsers"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="isEditMode ? '编辑用户' : '添加用户'"
      width="500px"
      :before-close="handleCloseDialog"
    >
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            :disabled="isEditMode"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEditMode">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="正常" value="normal" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'UserManagement',
  setup() {
    const loading = ref(false)
    const userDialogVisible = ref(false)
    const isEditMode = ref(false)
    const userFormRef = ref(null)
    const selectedUsers = ref([])
    const searchQuery = ref('')
    const statusFilter = ref('')
    const roleFilter = ref('')
    const currentPage = ref(1)
    const pageSize = ref(20)
    const totalUsers = ref(0)

    // 用户列表数据
    const users = ref([
      {
        id: 1,
        username: 'admin',
        email: 'admin@example.com',
        role: 'admin',
        status: 'normal',
        avatar: '',
        lastLoginTime: '2025-01-15 10:30:00',
        createTime: '2025-01-01 09:00:00',
        remark: '系统管理员'
      },
      {
        id: 2,
        username: 'user001',
        email: 'user001@example.com',
        role: 'user',
        status: 'normal',
        avatar: '',
        lastLoginTime: '2025-01-15 14:20:00',
        createTime: '2025-01-02 10:15:00',
        remark: '普通用户'
      },
      {
        id: 3,
        username: 'user002',
        email: 'user002@example.com',
        role: 'user',
        status: 'disabled',
        avatar: '',
        lastLoginTime: '2025-01-10 16:45:00',
        createTime: '2025-01-03 11:20:00',
        remark: '已禁用用户'
      }
    ])

    // 用户表单数据
    const userForm = reactive({
      id: null,
      username: '',
      email: '',
      password: '',
      role: '',
      status: 'normal',
      remark: ''
    })

    // 表单验证规则
    const userFormRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }

    // 过滤后的用户列表
    const filteredUsers = computed(() => {
      let filtered = users.value

      // 搜索过滤
      if (searchQuery.value) {
        filtered = filtered.filter(user => 
          user.username.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
          user.email.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
      }

      // 状态过滤
      if (statusFilter.value) {
        filtered = filtered.filter(user => user.status === statusFilter.value)
      }

      // 角色过滤
      if (roleFilter.value) {
        filtered = filtered.filter(user => user.role === roleFilter.value)
      }

      return filtered
    })

    // 监听过滤结果变化，更新总数
    watch(filteredUsers, (newVal) => {
      totalUsers.value = newVal.length
    }, { immediate: true })

    // 显示添加用户对话框
    const showAddUserDialog = () => {
      isEditMode.value = false
      resetUserForm()
      userDialogVisible.value = true
    }

    // 编辑用户
    const editUser = (user) => {
      isEditMode.value = true
      Object.assign(userForm, user)
      userDialogVisible.value = true
    }

    // 重置用户表单
    const resetUserForm = () => {
      Object.assign(userForm, {
        id: null,
        username: '',
        email: '',
        password: '',
        role: '',
        status: 'normal',
        remark: ''
      })
      if (userFormRef.value) {
        userFormRef.value.resetFields()
      }
    }

    // 关闭对话框
    const handleCloseDialog = (done) => {
      ElMessageBox.confirm('确定要关闭吗？')
        .then(() => {
          resetUserForm()
          done()
        })
        .catch(() => {})
    }

    // 保存用户
    const saveUser = () => {
      userFormRef.value.validate((valid) => {
        if (valid) {
          if (isEditMode.value) {
            // 编辑用户
            const index = users.value.findIndex(u => u.id === userForm.id)
            if (index !== -1) {
              users.value[index] = { ...userForm }
              ElMessage.success('用户信息更新成功')
            }
          } else {
            // 添加用户
            const newUser = {
              ...userForm,
              id: Date.now(),
              avatar: '',
              lastLoginTime: '未登录',
              createTime: new Date().toLocaleString()
            }
            users.value.push(newUser)
            ElMessage.success('用户添加成功')
          }
          userDialogVisible.value = false
          resetUserForm()
        }
      })
    }

    // 切换用户状态
    const toggleUserStatus = (user) => {
      const newStatus = user.status === 'normal' ? 'disabled' : 'normal'
      const action = newStatus === 'normal' ? '启用' : '禁用'
      
      ElMessageBox.confirm(`确定要${action}用户 ${user.username} 吗？`)
        .then(() => {
          user.status = newStatus
          ElMessage.success(`用户${action}成功`)
        })
        .catch(() => {})
    }

    // 删除用户
    const deleteUser = (user) => {
      ElMessageBox.confirm(`确定要删除用户 ${user.username} 吗？`)
        .then(() => {
          const index = users.value.findIndex(u => u.id === user.id)
          if (index !== -1) {
            users.value.splice(index, 1)
            ElMessage.success('用户删除成功')
          }
        })
        .catch(() => {})
    }

    // 批量删除用户
    const batchDeleteUsers = () => {
      if (selectedUsers.value.length === 0) {
        ElMessage.warning('请选择要删除的用户')
        return
      }

      ElMessageBox.confirm(`确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`)
        .then(() => {
          const selectedIds = selectedUsers.value.map(u => u.id)
          users.value = users.value.filter(u => !selectedIds.includes(u.id))
          selectedUsers.value = []
          ElMessage.success('批量删除成功')
        })
        .catch(() => {})
    }

    // 导出用户
    const exportUsers = () => {
      ElMessage.success('用户数据导出成功')
    }

    // 处理选择变化
    const handleSelectionChange = (selection) => {
      selectedUsers.value = selection
    }

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
    }

    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }

    // 处理当前页变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }

    onMounted(() => {
      totalUsers.value = users.value.length
    })

    return {
      loading,
      userDialogVisible,
      isEditMode,
      userFormRef,
      selectedUsers,
      searchQuery,
      statusFilter,
      roleFilter,
      currentPage,
      pageSize,
      totalUsers,
      users,
      filteredUsers,
      userForm,
      userFormRules,
      showAddUserDialog,
      editUser,
      resetUserForm,
      handleCloseDialog,
      saveUser,
      toggleUserStatus,
      deleteUser,
      batchDeleteUsers,
      exportUsers,
      handleSelectionChange,
      handleSearch,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #666;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.user-table {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.user-id {
  font-size: 12px;
  color: #999;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 15px;
  }
  
  .toolbar-left {
    width: 100%;
    justify-content: center;
  }
  
  .toolbar-right {
    width: 100%;
    flex-direction: column;
    gap: 10px;
  }
  
  .user-table {
    padding: 10px;
  }
}
</style> 